<?php
/**
 * Created by PhpStorm.
 * User: guoqiang
 * Date: 2020/06/08
 * Time: 10:23
 */

namespace app\api\controller\v18;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\AstroChange as AstroChangeModel;
use app\common\cachemodel\Fortune;
use app\common\cachemodel\IndexButton;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\astrolog\Astrolog;
use app\common\lib\ConfigManage;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\AppNotice;
use app\common\model\AstroChange;
use app\common\model\Recode as RecodeModel;
use app\common\model\Slide;
use app\everyday\controller\Index as FortuneIndex;
use Exception;
use think\Cache;
use think\Env;
use think\Log;

/**
 * @title 首页接口
 * @desc 新增天象日历青少年need_auth的权限状态字段 今日天象词条显示逻辑修改
 * @version 2.1.0
 * Class Index
 * @package app\api\controller\v18
 */
class Index extends Auth2
{
    protected $restActionList = ['index'];

    /**
     * @title 首页接口
     * @method GET
     * @desc 无需另外传参
     * @readme /doc/api/index/index.md
     * @return string
     * @throws ApiException
     * @throws Exception
     */
    public function index()
    {
        $isYoung = $this->user ? $this->user['young_model'] : false; // 是否是青少年模式
        $time_now = time();
        $in_sign = input('in_sign/d', 1);
        if ($this->user && $this->user['rid'])
        {  // 开启青少年模式时，禁止访问幸运星
            $luckyNeedAuth = $isYoung ? 3 : 2;
            $astroCalendarNeedAuth = $isYoung ? 3 : 0;

            $map = ['uid' => $this->user['id'], 'isself' => 1];
            $recode_info = (new RecodeModel())->getSelfRecode($map);

            if (!$recode_info || !$recode_info['sun'])
            {
                return show(406, '档案缺失请添加档案');
            }

            $in_sign = explode('-', $recode_info['sun'])[0];
        } else
        {
            // 未登录，已选择星座用户，展示今日天象信息
            $luckyNeedAuth = 2;
            $astroCalendarNeedAuth = 0;
            if (!in_array($in_sign, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
            {
                return show(408, '请选择星座');
            }
        }

        // 首页按钮
        $btns = (new IndexButton())->getIndexButton(['ver' => $this->headers['version'], 'app_type' => $this->headers['app-type']], true, $isYoung);
        if ($isYoung)
        {
            $articles = null;
            $slide = null;
        } else
        {
            // 首页轮播
            $slide = (new Slide())->getSlideVersion([]);
            foreach ($slide as $k => $datum)
            {
                $slide[$k]['image'] = $datum['image2'] ?? '';
                unset($slide[$k]['image2']);
            }
        }

        //获取公告相关信息
        $AppNotice = new AppNotice();
        $notice = $AppNotice->getNotice();
        if ($notice && (!$isYoung || ($notice['young_model'] ?? false)))
        {   // 如果为开启青少年模式 或者 青少年模式下也显示
            $notice['content'] = $notice['des'];
            //公告为jpg或gif时算出向上偏移比例【算法：（图片居中时距上的高度 - 蓝狐所给距上的高度）/ 模板或手机的高度】保留两位
            if (in_array($notice['img_type'], [2, 3]))
            {
                $notice['img_top_height'] = -0.07;//负数是向上偏移，正数是向下偏移
            }
            unset($notice['des'], $notice['young_model']);
        } else
        {
            $notice = null;
        }
        $revive_day = null;
        $fortune_cache = [];
        //若登录则计算今日运势获取三星数据
        if ($this->user['rid'])
        {
            try
            {
                $fortune_cache = (new Fortune())->fortuneDayHomeData($this->user['rid'],$time_now);
                //将今日运势图片替换为新图标
                $new_icon = explode('/', $fortune_cache['revive_day']['icon_url']);
                array_splice($new_icon, 5, 0, ['v2']);
                $fortune_cache['revive_day']['icon_url'] = implode('/', $new_icon);
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                Log::write('首页获取日运缓存数据错误:' . 'uid=[' . $this->user['id'] . ']' . $e->getMessage(), 'error');
                throw new ApiException('服务异常，请稍后再试~');
            }
            //若今日运势为3级
            if ((int)($fortune_cache['revive_day']['star_level'] ?? 0) === 3)
            {
                $revive_day = $fortune_cache['revive_day'];
                $fortune_cache = [];//目录配置里层获取今日运势是否计算开关控制，$fortune_cache为空，则里层需要计算
            }
        }
        //获取首页目录配置信息
        $indexConfig = ConfigManage::indexCategory($this->user, $in_sign, $this->headers['version'], $fortune_cache);
        $data = [
            'in_sign' => (int)$in_sign,
            'today_astro_tips' => $this->getTipCache(),
            'slides' => $slide,
            'buttons' => $btns,
            'fortune_category' => $indexConfig['fortune_category'],
            'article_category' => $indexConfig['article_category'],
            'lucky_planet_switch' => true,// 幸运星功能开关
            'notice' => $notice,
            'is_young_model' => $isYoung ? 1 : 2,
            'lucky_need_auth' => $luckyNeedAuth,
            'active_switch' => [
                'is_open' => false,
                'icon' => '',
                'target' => '',
                'link' => '',
                'width' => 0,
                'height' => 0
            ],
            'today_revive_day' => $revive_day,
            'astro_calendar_need_auth' => $astroCalendarNeedAuth
        ];
        $config = config('active.index_active');
        //若在活动时间内，开启
        if (active()['indexGift'] || ($time_now >= $config['start'] && $time_now <= $config['end']))
        {
            $data['active_switch'] = [
                'is_open' => false,
                'icon' => $config['icon'],
                'target' => 'link',
                'link' => Env::get('host.domain') . $config['link'],//大礼包h5
                'height' => 62
            ];
            // 仅针对V1.9.0和1.9.1开启首页幸运之城更新提示
            if (isset($this->headers['version']) && ($this->headers['version'] === '1.9.0' || $this->headers['version'] === '1.9.1'))
            {
                $data['active_switch']['is_open'] = true;
            }
        }

        // 登录后才做任务  VIP 每日任务
        if ($this->user)
        {
            (new ZlUserVip())->updateStarNum((int)$this->user['id'], 9);
        }

        return show(200, '首页加载成功', $data);
    }

    private function getTipCache()
    {
        $tipCacheKey = 'today_astro_tips:' . date('Ymd');

        $tip = Cache::get($tipCacheKey);

        if (!$tip)
        {
            $tip = $this->getTips();
            // 缓存今日天象信息
            Cache::set($tipCacheKey, $tip, 86400);
        }

        return $tip;
    }

    private function getTips()
    {
        //1、检测当天天象
        $astroChangeModel = new AstroChangeModel();
        $underwayAstro = $astroChangeModel->getChangeDayList(date('Y-m-d'), 8);

        if ($underwayAstro['listData'])
        {
            $strArray = [];
            foreach ($underwayAstro['listData'] as $v)
            {
                //若同时存在多天象，优先展示：太阳换座>X座新月>水星在X座逆行>金星X座逆行>金星进入X座>水星进入X座
                switch ($v['type'])
                {
                    case 1: // 行星换座
                        if ($v['pid'] == 0)
                        {
                            return $v['text']; // 太阳换座
                        }
                        if (in_array($v['pid'], [2, 3]))
                        {   // 水星 和 金星 换座
                            $strArray[strtotime($v['time']) + 1000000] = $v['text'];
                        }
                        break;
                    case 2: // 顺行 speed = 1｜ speed = 2逆行
                        if (in_array($v['pid'], [2, 3]) && $v['speed'] == 2)
                        { // 水星 和 金星 逆行
                            $strArray[strtotime($v['time'])] = $v['text'];
                        }
                        break;
                    case 5: // 新月
                        $strArray[strtotime($v['time']) - 1000000] = $v['text'];
                        break;
                    default:
                }
            }
            if ($strArray)
            {
                ksort($strArray);

                return current($strArray);
            }
        }
        // 如果今天没有重要天象 -> 则显示太阳运行在什么星座

        //2、X座新月（输出：某某座新月）
        //3、水、金是否逆行输出：某星逆行）
        //4、日水金是否与昨天24点的星座不同（输出：某某星进入某某座）
        //5、太阳在哪个星座（输出：太阳在某某座）
        // 若同时存在多天象，优先展示：太阳换座>X座新月>水星在X座逆行>金星X座逆行>金星进入X座>水星进入X座
        // 若无以上天象，则展示太阳运行在XX座
        $time = time();

        $timeinfo = ['year' => date('Y', $time), 'month' => date('m', $time), 'day' => date('d', $time), 'hour' => 0, 'minute' => 0,];

        $timeinfo['timezone'] = 8;

        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'], $timeinfo['minute'], 0, $timeinfo['month'], $timeinfo['day'], $timeinfo['year']) ? 1 : 0;
        // 默认北京
        $timeinfo['longitude'] = 116.443153;
        $timeinfo['latitude'] = 39.921466;

        // 获取天象盘数据
        $nowData = Astrolog::getInstance()
            ->setExecPrefix(config('astrolog.prefix'))
            ->setAdvance($timeinfo)
            ->setUserSetting(config('astroset.setting1'))
            ->setGetDatas(['now'])
            ->getAstroDatas()
            ->getDatas('now');

        $tx_planet = is_array($nowData['planets']) ? $nowData['planets'] : json_decode(json_encode($nowData['planets'], true), true);// 天象行星数据

        $sun_deg = $tx_planet[0]['deg'];// 太阳的度数
        $sun_speed = $tx_planet[0]['speed'];// 太阳的度数

        $start_sign = Util::modSignId(floor($sun_deg / 30) + 1);
        $end_sign = Util::modSignId(floor(($sun_deg + $sun_speed) / 30) + 1);

        if ($start_sign == $end_sign)
        {
            $sign_name = explode('|', config('astrolog.sign_name')[$start_sign])[3];

            $tip = '太阳运行在' . $sign_name;
        } else
        {
            $sign_name = explode('|', config('astrolog.sign_name')[$end_sign])[3];

            return '太阳进入' . $sign_name;
        }

        return $tip;
    }
}
